<?php

class Model_Listing_Commercial extends Model_Listing implements Model_Listing_Interface
{
    const MANAGEMENT_FEE_MIN = 0;
    const MANAGEMENT_FEE_MAX = 150000;
    const GOVERNMENT_FEE_MIN = 0;
    const GOVERNMENT_FEE_MAX = 150000;
    const SIZE_MIN = 0;
    const SIZE_MAX = 5000;
    const BUILDING_AGE_MIN = 0;
    const BUILDING_AGE_MAX = 40;
    protected static  $_collection = 'listing';

    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
        'foc'  => array('Array'), //Fit-Out Conditions
        'vie'  => array('Array'), //view
        'av'   => array('Array'), //Availability
        'acs'  => array('Array'), //Air Conditioning System
        'to'   => array('Array'), //Toilet
        'bf'   => array('Array'), //Building Facilities
        'cpf'  => array('Array'), //CarParking Facilities
    );

    protected $_category = array();

    public function __construct($data = array(), $config = array()) {
        static::$_transcript = array_merge(array(
            'ao'  => 'agency_owner',
            'soa' => 'sole_agency',
            'an'  => 'agent_name',
            'ai'  => 'agent_id',
            'ap'  => 'agent_phone',
            'ae'  => 'agent_email',
            'sp'  => 'sale_price',
            'pn'  => 'price_negotiable',
            'sl'  => 'sale_lease',
            'led' => 'lease_enddate',
            'clp' => 'current_lease_price',
            'rp'  => 'rent_price',
            'rmf' => 'rent_include_mngt_fee',
            'sz'  => 'size',
            'tsz'  => 'total_size',
            'os'  => 'ownership',
            'bla' => 'building_age',
            'prt' => 'property_type',
            'fz'  => 'floor_zone',
            'mf'  => 'management_fee',
            'gf'  => 'government_fee',
            'arl1'  => 'area_l1',
            'arl2'  => 'area_l2',
            'foc'  => 'fitoutconditions',
            'vie'  => 'views',
            'av'  => 'availability',
            'acs'  => 'airconsystem',
            'to'  => 'toilet',
            'bf'  => 'buildingfacilities',
            'cpf'  => 'carparkingfacilities',
            'tfa'  => 'typicalfloorarea',
            'ch'  => 'ceilingheight',
            'pl'  => 'passengelifts',
            'sel'  => 'servicelifts',
            'ns'  => 'numberstores',
            'fs'  => 'flooringsystem',
            'ahw'  => 'airconhoursweek',
            'ahs'  => 'airconhourssaturday',
            'spps'  => 'salepricepersqft',
            'spt'  => 'salepricetotal',
            'rpps'  => 'rentpricepersqft',
            'rpt'  => 'rentpricetotal',
        ), static::$_transcript);
        parent::__construct($data, $config);
    }
	
	public static function getTranslationFormField()
    {
        $arr = array(
			'tl_en' =>'text',
			'cs_en' =>'textarea',
		);
		
		return $arr;
    }
	
    public function postAnAddForm($options = array()) {
        $options = array_merge($options, array('category' => $this->category));
        return new Listing_Form_PostAnAddCommercialForm($options);
    }

    public function getAdDetailPartialName()
    {
        return 'customization/commercial.phtml';
    }

    public function getAdPreviewPartialName()
    {
        return $this->getAdDetailPartialName();
    }


    public static function getSearchResultPartialName()
    {
        return 'commercial';
    }

    public static function getRefineSearchForm()
    {
        return new Search_Form_CommercialRefineForm();
    }

    public static function processRefineSearchForm(&$get, $page, $per_page, &$query, &$fields, &$additionalParameters)
    {

        //echo '<pre>';print_r($_GET);exit;

        //$q       = isset($_GET['keyword']) ? strtolower($_GET['keyword']) : false;
        $results = false;
        if(empty($fields)) {
            $fields  = array('description', 'title', 'area_l2_name', 'area_l1_name', 'street');
        }
        if(empty($additionalParameters)) {
            $additionalParameters = array();
        }
        $values  = array();
        //$get     = $_GET;
/*
        if (!empty($get['keyword'])) {
            $values['description'] = ' '.strtolower($get['keyword']).' ';
            $values['title']       = ' '.strtolower($get['keyword']).' ';
        }
*/
        
        $search_terms = self::getSearchTextTerms();
        
        $exact_search_terms = self::getExactSeachTerms();
        
        $q      = '';
        $qq     = empty($_GET['keyword']) ? '' : $_GET['keyword'];
        $to_add = ' ';

        //add the username
        if (!empty($get['keyword'])) {
            //$q = '(username_lower:"'.$get['keyword'].'"^50.0) ';
        }

        if (!empty($exact_search_terms)) {
            foreach($exact_search_terms as $name => $val) {
                foreach($val as $k => $v) {
                    if (preg_match('#('.trim($v).')#i', $get['keyword'], $match)) {
                        //var_dump($match, $v, $get['keyword'], str_ireplace( $v, '', $get['keyword']));
                        $get['keyword'] = str_ireplace( $v, '', $get['keyword']);
                        $q .= $to_add.str_replace('_name', '', $name) .':'.$k.'^5.0 ';
                        $to_add = ' OR ';
                    }
                }
            }
            if (!empty($q) && !empty($tmp)) {
                $q = ' OR ('.$tmp.') ';
            }
        }
        
        $pattern = '#(?<=([0-9]))\s+bedroom[s]?#iu';
        if (preg_match($pattern, strtolower($get['keyword']), $match)) {
            $qq = str_ireplace($match[1].$match[0], '"'.$match[1].$match[0].'"', $qq);
            $get['keyword'] = str_ireplace($match[1].$match[0], '', $get['keyword']);
            $tmp = ' bedroom:'.trim($match[1]).'^9.0 ';
            if (!empty($q)) {
                $q .= ' OR ('.$tmp.') ';
            } else {
                $q = $tmp;
            }
        }
        
        $to_add = ' ';
        
        //remove quoted words and add them to q
        $bak = $get['keyword'];
        
        
        $arr = preg_match_all('#\"(.*?)\"#i', $get['keyword'], $match);
        foreach ($match[1] as $v) {
            $q .= ' AND "'.$v.'"';
        }
        $get['keyword'] = preg_replace('#"(.*?)"#i', '', $get['keyword']);
        $qf = '';
        foreach($search_terms as $v => $weight) {
            $qf .= $v.'^'.$weight.' ';
        }
        
        if (!empty($qf)) {
            $additionalParameters['qf'] = $qf;
        }
        if (!empty($qq)) {
            $additionalParameters['qq']   = $qq;
        }  
        
        $get['keyword'] = trim($get['keyword']);
        if (!empty($get['keyword'])) {
            if (!empty($q)) {
                $q.=' OR ';
            }
            $q .='(';
            foreach ($fields as $f) {
                $list = explode(' ', trim($get['keyword']));
                foreach($list as $vl) {
                    if (!empty($vl)) {
                        $q .= $to_add.''.$f.':'.$vl;
                        $to_add = ' OR ';
                    }
                }
            }
            $q.=') ';
        }
        
        
        $q.= ' OR _query_:"{!dismax qf=$qf v=$qq}" ';
        
        if (empty($_GET['keyword'])) {
            $q = '*:*';
        }
               /* 
       // echo '<pre>';print_r($values);
        foreach($values as $k => $val) {
            if (is_array($val)) {
                $tmp = array();
                foreach($val as $k2 => $v2) {
                    $tmp[] = ' '.$k.':'.$v2;
                }
                $values[$k] = '('.implode(' OR ', $tmp).')';
            } else {
                $values[$k] = ' '.$k.':'.$val;
            }
        }

        if (!empty($values)) {
            $query = implode(' ', $values);
        } else {
            $query = '*:*';
        }
*/
        $query = $q;
        
        $get['sort'] = empty($get['sort']) ? '' : $get['sort'];

        switch ($get['sort']) {
            case 'highest':
                $get['sort'] = 'highest';
                $sort = 'price desc';
                break;
            case 'lowest':
                $get['sort'] = 'lowest';
                $sort = 'is_free asc, price asc';
                break;
            case 'rel':
                $get['sort'] = 'rel';
                $sort = 'score desc';
                break;
            case 'recent':
                $get['sort'] = 'recent';
                $sort = 'posted_at desc';
                break;
            case 'status':
                $get['sort'] = 'status';
                $sort = 'status desc';
                break;
            default:
                if (!empty($get['keyword'])) {
                    $get['sort'] = 'rel';
                    $sort         = 'score desc';
                } else {
                    $get['sort'] = 'recent';
                    $sort         = 'posted_at desc';
                }
        }

        $additionalParameters['fl']   = '*,score';
        $additionalParameters['sort'] = $sort;
        
        $fq         = '';
        if(!empty($additionalParameters['fq'])) {
            $fq = $additionalParameters['fq'];
        }
        
        $valuesplus = array();
        if (!empty($get['has_image'])) {
            $valuesplus['has_image'] = true;
        }


        // Sale by
        $buy_rent = '';
        if (!empty($get['wantto_comm'])) {
            $buy_rent = $get['wantto_comm'];
        }
        elseif (!empty($get['want_to']['buy_rent'])) {
            $buy_rent = $get['want_to']['buy_rent'];
        }

        // Sale by
        if (!empty($buy_rent)) {
            if ($buy_rent == 'Buy') {
                //Sale Category
                $sales = array();
                $sale = Model_Category::one(array('id' => 'c558'));
                $sales1 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c552'));
                $sales2 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c440'));
                $sales3 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c573'));
                $sales4 = $sale->_id;
                $category = ' +(category:'.$sales1.' OR category:'.$sales2.' OR category:'.$sales3.' OR category:'.$sales4.') ';
                //$category = ' +category:'.$sales3.' ';
            }
            elseif ($buy_rent == 'Rent') {
                $rents = array();
                $rent = Model_Category::one(array('id' => 'c557'));
                $rents1 = $rent->_id;
                $rent = Model_Category::one(array('id' => 'c551'));
                $rents2 = $rent->_id;
                $rent = Model_Category::one(array('id' => 'c442'));
                $rents3 = $rent->_id;
                $rent = Model_Category::one(array('id' => 'c572'));
                $rents4 = $rent->_id;
                $category = ' +(category:'.$rents1.' OR category:'.$rents2.' OR category:'.$rents3.' OR category:'.$rents4.') ';
            }
        }

        // Type
        if (!empty($get['property_type'])) {
            $valuesplus['property_type'] = $get['property_type'];
        }

        // Sale by
        if (!empty($get['agency_owner_comm'])) {
            $agency_owner = $get['agency_owner_comm'];
        }
        elseif (!empty($get['seller']['saleby'])) {
            $agency_owner = $get['seller']['saleby'];
        }

        if (!empty($agency_owner)) {
            if ($agency_owner == 'Agency') {
                $valuesplus['agency_owner'] = '1';
            }
            elseif ($agency_owner == 'Owner') {
                $valuesplus['agency_owner'] = '0';
            }
        }

        //force only commercial
        //$valuesplus['type_obj_s'] = 'Model_Listing_Commercial';
        if(strpos($fq, '+type_obj_s') === false) {
            $valuesplus['type_obj_s'] = 'Model_Listing';
        }
        

        //Price (Sale/Buy)
        //Price (Sale/Buy)
        if (isset($get['price']) && isset($get['price-1'])) {
            $price  = $get['price'];
            $price1 = $get['price-1'];
        }

        if (isset($price) && isset($price1)) {
            $test1 = false;$test2 = false;
            if (empty($price1)) {
                $price1 = '*';
                $test1 = true;
            }
            if (empty($price)) {
                $price = '0';
                $test2 = true;
            }

            if (!$test1 || !$test2) {
                // Check if this is to rent or to buy
                if ($buy_rent === 'Rent') {
                    $valuesplus['rent_price'] = '['.intval(str_replace(',', '', $price)).' TO '.str_replace(',', '', $price1).']';
                } elseif ($buy_rent === 'Buy') {
                    $valuesplus['sale_price'] = '['.intval(str_replace(',', '', $price)).' TO '.str_replace(',', '', $price1).']';
                } else {
                    $valuesplus['price'] = '['.intval(str_replace(',', '', $price)).' TO '.str_replace(',', '', $price1).']';
                    //$valuesplus['sale_price'] = '['.$price.' TO '.$price1.']';
                }
            }
        }

        // Property Type
        //if (!empty($get['key_search_tools']['type'])) {
        //    $valuesplus['property_type'] = $get['key_search_tools']['type'];
        //}
        
        // Area
        if (!empty($get['area_l1'])) {
            $valuesplus['area_l1'] = $get['area_l1'];
        }
        
        // District
        if (!empty($get['area_l2'])) {
            $valuesplus['area_l2'] = $get['area_l2'];
        }
       
        if (!empty($get['city'])) {
            $valuesplus['city'] = (int) $_GET['city'];
        }
       
        
        // Includes management and government fees
        if (!empty($get['optional']['includes_fees'])) {
            $valuesplus['rent_include_mngt_fee'] = $get['optional']['includes_fees'];
        }
                
        // Management Fee and government Fee
        if (!empty($get['want_to']['buy_rent'])) {
            if ($get['want_to']['buy_rent'] == 'Rent') {
                if (isset($get['optional-management_fee']) && isset($get['optional-management_fee-1'])) {
                    $test1 = false;$test2 = false;
                    if ($get['optional-management_fee-1'] == Model_Listing_Commercial::MANAGEMENT_FEE_MAX) {
                        $get['optional-management_fee-1'] = '*';
                        $test1 = true;
                    }
                    if ($get['optional-management_fee'] == Model_Listing_Commercial::MANAGEMENT_FEE_MIN) {
                        $get['optional-management_fee'] = '0';
                        $test2 = true;
                    }
                    if (!$test1 || !$test2) {
                       $valuesplus['management_fee'] = '['.$get['optional-management_fee'].' TO '.$get['optional-management_fee-1'].']';
                    }
                }
                if (isset($get['optional-government_fee']) && isset($get['optional-government_fee-1'])) {
                    $test1 = false;$test2 = false;
                    if ($get['optional-government_fee-1'] == Model_Listing_Commercial::GOVERNMENT_FEE_MAX) {
                        $get['optional-government_fee-1'] = '*';
                        $test1 = true;
                    }
                    if ($get['optional-government_fee'] == Model_Listing_Commercial::GOVERNMENT_FEE_MIN) {
                        $get['optional-government_fee'] = '0';
                        $test2 = true;
                    }
                    if (!$test1 || !$test2) {
                       $valuesplus['government_fee'] = '['.$get['optional-government_fee'].' TO '.$get['optional-government_fee-1'].']';
                    }
                }
            }
        }

        // Buy with lease
        if (!empty($get['buy_with_lease'])) {
            $valuesplus['sale_lease'] = $get['buy_with_lease'];
        }
        // Price negotiable
        if (!empty($get['optional']['price_negotiable'])) {
            $valuesplus['price_negotiable'] = $get['optional']['price_negotiable'];
        }
        // Floor Zone
        if (!empty($get['floor_zone'])) {
            $valuesplus['floor_zone'] = $get['floor_zone'];
        }

        //Size
        if (isset($get['size']) && isset($get['size-1'])) {
            $size  = $get['size'];
            $size1 = $get['size-1'];
        }

        if (isset($size) && isset($size1)) {
            $test1 = false;$test2 = false;
            if ($size1 == Model_Listing_Commercial::SIZE_MAX) {
                $size1 = '*';
                $test1 = true;
            }
            if ($size == Model_Listing_Commercial::SIZE_MIN) {
                $size = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['size'] = '['.$size.' TO '.$size1.']';
            }
        }
        
        //Building Age
        if (isset($get['building_age']) && isset($get['building_age-1'])) {
            $building_age  = $get['building_age'];
            $building_age1 = $get['building_age-1'];
        }

        if (isset($building_age) && isset($building_age1)) {
            $test1 = false;$test2 = false;
            if ($building_age1 == Model_Listing_Commercial::BUILDING_AGE_MAX) {
                $building_age1 = '*';
                $test1 = true;
            }
            if ($building_age == Model_Listing_Commercial::BUILDING_AGE_MIN) {
                $building_age = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['building_age'] = '['.$building_age.' TO '.$building_age1.']';
            }
        }
        
        // Fit-Out Conditions
        if (!empty($get['optional']['fitoutconditions'])) {
            $valuesplus['fitoutconditions'] = $get['optional']['fitoutconditions'];
        }
        // View
        if (!empty($get['optional']['views'])) {
            $valuesplus['property_views'] = $get['optional']['views'];
        }
        // Toilet
        if (!empty($get['optional']['toilet'])) {
            $valuesplus['toilet'] = $get['optional']['toilet'];
        }
        // Availability
        if (!empty($get['optional']['availability'])) {
            $valuesplus['availability'] = $get['optional']['availability'];
        }
        // Air Conditioning System
        if (!empty($get['optional']['airconsystem'])) {
            $valuesplus['airconsystem'] = $get['optional']['airconsystem'];
        }
        // Building/Street Name
        if (!empty($get['street'])) {
            $valuesplus['street'] = ''.$get['street'].'';
        }

        foreach($valuesplus as $k => $val) {
          $valuesplus[$k] = '+'.$k.':'.$val.' ';
        }

        if (!empty($category)) {
            $fq .= $category;
        }

        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }        

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
        //echo '<PRE>';print_r($valuesplus);exit;
    }

    public static function getPropertyType($id = null)
    {
        $res = array('' => 'All') + self::getPropertyTypePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getPropertyTypePostAd()
    {
        return array(
            0 => '写字楼',
                1 => '商务中心',
                3 => '商住公寓',
                4 => '商店',
        );
    }

    public static function getFloorZone($id = null)
    {
        $res = array('' => 'All') + self::getFloorZonePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getFloorZonePostAd()
    {
        $view = Zend_Registry::get('Zend_View');
        return array(
            '' => 'Select',
            1 => 'Groung floor',
            2 => 'Low',
            3 => 'Medium',
            4 => 'High',
            5 => 'Very High'
        );
    }
    
    public static function getBuildingAge($id = null)
    {
        $res = array('' => 'All') + self::getBuildingAgePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getBuildingAgePostAd()
    {
        $array = array();
        $array[''] = 'Select';
        for ($i=1;$i<=50;$i++)
        {
            $array[$i] = $i;
        }
        return $array;
    }

    public static function getNumberofStores($id = null)
    {
        $res = array('' => 'All') + self::getNumberofStoresPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getNumberofStoresPostAd()
    {
        $array = array();
        $array[''] = 'Select';
        for ($i=1;$i<=90;$i++)
        {
            $array[$i] = $i;
        }
        return $array;
    }

    public static function getHours($id = null)
    {
        $res = array('' => 'All') + self::getNumberofStoresPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getHoursPostAd()
    {
        $array = array();
        $array[''] = 'Select';
        for ($i=0;$i<=24;$i++)
        {
            if ($i == 0) {
                $array['12:00'] = '12:00';
            }
            else {
                $array[$i.':00'] = $i.':00';
            }
        }
        return $array;
    }

    public static function getFitoutConditions($id = null)
    {
        $res = array('' => 'All') + self::getFitoutConditionsSearch();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getFitoutConditionsSearch()
    {
        return array(
            '' => 'All',
            1 => 'Bare Shell',
            2 => 'Carpet',
            3 => 'Ceiling',
            4 => 'Fuly Fitted',
            5 => 'Furnished'
        );
    }

    public static function getViews($id = null)
    {
        $res = array('' => 'All') + self::getViewsSearch();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getViewsSearch()
    {
        return array(
            '' => 'All',
            1 => 'City',
            2 => 'Green/Mountain',
            3 => 'Harbour/Sea',
            4 => 'Open',
            5 => 'Race Course'
        );
    }

    public static function getToilet($id = null)
    {
        $res = array('' => 'All') + self::getToiletSearch();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getToiletSearch()
    {
        return array(
            '' => 'All',
            1 => 'Private',
            2 => 'Public'
        );
    }
    public static function getAvailabilitySearch($id = null)
    {
        $res = array('' => 'Select') + self::getAvailability();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }
    

    public static function getAvailability()
    {
        return array(
            '' => 'All',
            1 => 'Negotiable',
            2 => 'Immediate',
            3 => 'One month',
            4 => 'Two months'
        );        
    }

    public static function getAirConditioningSystemSearch($id = null)
    {
        $res = array('' => 'Select') + self::getAirConditioningSystem();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }


    public static function getAirConditioningSystem()
    {
        $view = Zend_Registry::get('Zend_View');
        return array(
            1 => 'air-con-central',
            2 => 'Split Type'
        );
    }

    public static function getBuildingFacilities($id = null)
    {
        $res = array(
            1 => 'Banks',
            2 => 'Coffee Shop',
            3 => 'Conference Facilities',
            4 => 'Curtain Wall',
            5 => 'Health Club',
            6 => 'Hotels',
            7 => 'Serviced Apartment',
            8 => 'Shopping Arcade'
        );
        if ($id !== null) {
            return $res[$id];
        }
        return $res;        
    }

    public static function getCarparkingFacilities($id = null)
    {
        $res = array(
            1 => 'Covered Carpark',
            2 => 'Drive Through Drop-off Area',
            3 => 'Hourly Paid Carpark',
            4 => 'Loading/Unloading Area',
            5 => 'Open Carpark',
            6 => 'Valet Parking'
        );
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;        
    }

    public static function getFlooringSystem($id = null)
    {
        $res = array('' => 'All') + self::getFlooringSystemPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getFlooringSystemPostAd()
    {
        return array(
            '' => 'Select',
            1 => 'Raised',
            2 => 'Non-Raised'
        );
    }

    public static function getOwnerShip($id = null)
    {
        $res = array('' => 'All') + self::getOwnerShipPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        return $res;
    }

    public static function getOwnerShipPostAd()
    {
        return array(
            '' => 'Select',
            1 => 'ownership-single',
            2 => 'Stratified',
        );
    }
    
    

    public static function getSearchTextTerms() 
    {
        return array(
            'description'               => '1.0', 
            'title'                     => '7.0', 
            'bedroom'                   => '9.0', 
            'area_l2_name'             => '9.0',
            'street'                    => '7.0',
            'property_type_name'        => '5.0',
            'fitoutconditions_name'     => '5.0',
            'availability_name'         => '5.0',
            'airconsystem_name'         => '5.0',            
            'toilet_name'               => '5.0',
            'buildingfacilities_name'   => '5.0',
            'carparkingfacilities_name' => '5.0',
            'flooringsystem_name'       => '5.0',
            'ownership_name'            => '5.0',
        );
    }    
    
    /*
     * return a list of all the possible values that should be extracted from the keyword search and be specified as exact term
     * 
     */
    public static function getExactSeachTerms() 
    {
       return array(
                'property_type_name'  => self::getPropertyType(),
                'fitoutconditions_name'     => self::getFitoutConditions(),
                'availability_name'     => self::getAvailability(),
                'airconsystem_name'     => self::getAirConditioningSystem(),
                'toilet_name'         => self::getToilet(),
                'buildingfacilities_name'        => self::getBuildingFacilities(),
                'carparkingfacilities_name'          => self::getCarparkingFacilities(),
                'flooringsystem_name' => self::getFlooringSystem(),
                'ownership_name' => self::getOwnerShip()
           );
    }
        
    public function getSolrDocument($document = null)
    {
        if (!$document instanceof Apache_Solr_Document) {
            $document = new Apache_Solr_Document();
        }
        $view = Zend_Registry::get('Zend_View');
     
        
        //$document->price_negotiable         = (int)$this->pn;
        $document->sale_lease               = (string)$this->sl;
        $document->lease_enddate            = (string)$this->led;
        $document->current_lease_price      = (string)$this->clp;
        $document->rent_include_mngt_fee    = (string)$this->rmf;
        $document->size                     = (int)$this->sz;
        $document->building_age             = (int)$this->bla;
        
        if (!empty($this->prt)) {
            foreach ((array)$this->prt as $data) {
                $document->addField('property_type', (int)$data);
                $document->addField('property_type_name', self::getPropertyType($data));
                $document->addField('property_type_name', $view->t(self::getPropertyType($data), Model_Translate::TC));
            }
        }
        
        //$document->floor_zone               = (string)$this->fz;
        if (!empty($this->fz)) {
            $document->floor_zone        = (string)$this->fz;
            $document->addField('floor_zone_name', self::getFloorZone($this->fz));
            $document->addField('floor_zone_name', $view->t(self::getFloorZone($this->fz), Model_Translate::TC));
        }
        
        $document->management_fee            = (int)$this->mf;
        $document->government_fee           = (int)$this->gf;

        $document->typicalfloorarea         = (int)$this->tfa;
                
        $document->ceilingheight            = (int)$this->ch;
        
        $document->passengelifts            = (int)$this->pl;
        $document->servicelifts             = (int)$this->sel;
        $document->numberstores             = (int)$this->ns;
        //$document->flooringsystem           = (string)$this->fs;
        if (!empty($this->fs)) {
            $document->flooringsystem        = (int)$this->fs;
            $document->addField('flooringsystem_name', self::getFlooringSystem($this->fs));
            $document->addField('flooringsystem_name', $view->t(self::getFlooringSystem($this->fs), Model_Translate::TC));
        }        
        $document->airconhoursweek          = (string)$this->ahw;

        $document->airconhourssaturday      = (string)$this->ahs;
        $document->salepricepersqft         = (int)$this->spps;
        $document->salepricetotal           = (int)$this->spt;
        $document->rentpricepersqft         = (int)$this->rpps;
        $document->rentpricetotal           = (int)$this->rpt;

        if (!empty($this->os)) {
            $document->ownership        = (int)$this->os;
            $document->addField('ownership_name', self::getOwnerShip($this->os));
            $document->addField('ownership_name', $view->t(self::getOwnerShip($this->os), Model_Translate::TC));
        }        
        foreach ((array)$this->foc as $data) {
            $document->addField('fitoutconditions', (int)$data);
            $document->addField('fitoutconditions_name', self::getFitoutConditions($data));
            $document->addField('fitoutconditions_name', $view->t(self::getFitoutConditions($data), Model_Translate::TC));
        }
        foreach ((array)$this->av as $data) {
            $document->addField('availability', (int)$data);
            $document->addField('availability_name', self::getAvailabilitySearch($data));
            $document->addField('availability_name', $view->t(self::getAvailabilitySearch($data), Model_Translate::TC));            
        }
        foreach ((array)$this->acs as $data) {
            $document->addField('airconsystem', (int)$data);
            $document->addField('airconsystem_name', self::getAirConditioningSystemSearch($data));
            $document->addField('airconsystem_name', $view->t(self::getAirConditioningSystemSearch($data), Model_Translate::TC));
        }
        foreach ((array)$this->to as $data) {
            if (!empty($data)) {
                $document->addField('toilet', (string)$data);
                $document->addField('toilet_name', self::getToilet($data));
                $document->addField('toilet_name', $view->t(self::getToilet($data), Model_Translate::TC));            
            }
        }
        foreach ((array)$this->bf as $data) {
            $document->addField('buildingfacilities', (string)$data);
            $document->addField('buildingfacilities_name', self::getBuildingFacilities($data));
            $document->addField('buildingfacilities_name', $view->t(self::getBuildingFacilities($data), Model_Translate::TC));            
        }
        foreach ((array)$this->cpf as $data) {
            $document->addField('carparkingfacilities', (string)$data);
            $document->addField('carparkingfacilities_name', self::getCarparkingFacilities($data));
            $document->addField('carparkingfacilities_name', $view->t(self::getCarparkingFacilities($data), Model_Translate::TC));            
        }
        
        return parent::getSolrDocument($document);
    }
    public function checkPerTypeDataSanity()
    {
    	$count = 0;
    	$missing = array();
    	$to_save= array();
    	//echo "adasda";exit();
    	//call the checker for basic info
    	$arr = parent::checkPerTypeDataSanity();    	//$this->checkCommonDataSanity(); 
		if(!empty($arr)){   
			//merge missings	
	    	$missing = array_merge($missing, $arr['errors']);
	    	
			//use parent's count
	    	$count = $arr['error_count'];
    	}
		//size
		if(empty($this->sz)){
			$count++;
			$missing['size'][] = 'no size';
		}
		//building age
		if(!empty($this->bla) && !array_key_exists($this->bla, $this->getBuildingAgePostAd())){
			$count++;
			$missing['building age'][] = 'building age value not existing (bla: '.$this->bla.')';
		}
		//property type
		if(!empty($this->prt) && !array_key_exists($this->prt, $this->getPropertyTypePostAd())){
			$count++;
			$missing['property type'][] = 'property type value not existing (prt: '.$this->prt.')';
		}
		//floor zone
		if(!empty($this->fz) && !array_key_exists($this->fz, $this->getFloorZonePostAd())){
			$count++;
			$missing['floor zone'][] = 'floor zone value not existing (fz: '.$this->fz.')';
		}
		//views
		if(!empty($this->vie) && !is_array($this->vie)){
			$count++;
			$missing['views'][] = "value is not an array";//'views value not exist (vie: '.$this->vie.')';
		}
		//ownership
		if(!empty($this->os) && !array_key_exists($this->os, $this->getOwnerShipPostAd())){
			$count++;
			$missing['ownership'][] = 'ownership value not exist (os: '.$this->os.')';
		}
		//fitoutconditions
		if(!empty($this->foc) && !is_array($this->foc)){
			$count++;
			$missing['fitoutconditions'][] = "value is not an array";//'fitoutconditions value not exist (foc: '.$this->foc.')';
		}
		//availability
		if(!empty($this->av) && !is_array($this->av)){
			$count++;
			$missing['availability'][] = "value is not an array";//'availability value not exist (av: '.$this->av.')';
		}
		//airconsystem
		if(!empty($this->acs) && !is_array($this->acs)){
			$count++;
			$missing['airconsystem'][] = "value is not an array";//'airconsystem value not exist (acs: '.$this->acs.')';
		}
		//toilet
		if(!empty($this->to) && !is_array($this->to)){
			$count++;
			$missing['toilet'][] = "value is not an array";//'toilet value not exist (to: '.$this->to.')';
		}
		//buildingfacilities
		if(!empty($this->bf) && !is_array($this->bf)){
			$count++;
			$missing['buildingfacilities'][] = "value is not an array";//'buildingfacilities value not exist (bf: '.$this->bf.')';
		}
		//carparkingfacilities
		if(!empty($this->cpf) && !is_array($this->cpf)){
			$count++;
			$missing['carparkingfacilities'][] = "value is not an array";//'carparkingfacilities value not exist (cpf: '.$this->cpf.')';
		}
		//numberstores
		if(!empty($this->ns) && !array_key_exists($this->ns, $this->getNumberofStores())){
			$count++;
			$missing['numberstores'][] = 'numberstores value not exist (ns: '.$this->ns.')';
		}
		//flooringsystem
		if(!empty($this->fs) && !array_key_exists($this->fs, $this->getFlooringSystem())){
			$count++;
			$missing['flooringsystem'][] = 'flooringsystem value not exist (fs: '.$this->fs.')';
		}
		//airconhoursweek
		if(!empty($this->ahw) && !array_key_exists($this->ahw, $this->getAirConditioningSystem())){
			$count++;
			$missing['airconhoursweek'][] = 'airconhoursweek value not exist (ahw: '.$this->ahw.')';
		}
		//airconhourssaturday
		if(!empty($this->ahs) && !array_key_exists($this->ahs, $this->getAirConditioningSystem())){
			$count++;
			$missing['airconhourssaturday'][] = 'airconhourssaturday value not exist (ahs: '.$this->ahs.')';
		}
		if (!empty($missing)) {
	        $to_save['ls'] = $this->_id;
	        $to_save['errors'] = $missing;
	        $to_save['error_count'] = $count;
	    }
        return $to_save;       
    }

    public function exportRest($compressed = false)
    {
        $res = parent::exportRest($compressed);
        $view = Zend_Registry::get('Zend_View');


        $res['type'] = 'commercial';

        if ($compressed) {
            return $res;
        }


        $res['price_negotiable']         = !empty($this->pn) ? '1' : '0';
        $res['sale_lease']               = (string)$this->sl;
        $res['lease_enddate']            = (string)$this->led;
        $res['current_lease_price']      = (string)$this->clp;
        $res['rent_include_mngt_fee']    = (string)$this->rmf;
        $res['size']                     = (string)$this->size;
        $res['building_age']             = (string)$this->bla;
        
        if (!empty($this->prt)) {
            foreach ((array)$this->prt as $data) {
                $res['property_type'] = (string)$data;
                $res['property_type_en'] = self::getPropertyType($data);
                $res['property_type_tc'] = $view->t(self::getPropertyType($data), Model_Translate::TC);
            }
        }
        
        if (!empty($this->fz)) {
            $res['floor_zone']    = (string)$this->fz;
            $res['floor_zone_en'] = self::getFloorZone($this->fz);
            $res['floor_zone_tc'] = $view->t(self::getFloorZone($this->fz), Model_Translate::TC);
        }
        
        $res['management_fee']           = (string)$this->mf;
        $res['government_fee']           = (string)$this->gf;

        $res['typicalfloorarea']         = (string)$this->tfa;
                
        $res['ceilingheight']            = (string)$this->ch;
        
        $res['passengelifts']             = (string)$this->pl;
        $res['servicelifts']              = (string)$this->sel;
        $res['numberstores']              = (string)$this->ns;

        if (!empty($this->fs)) {
            $res['flooringsystem']       = (string)$this->fs;
            $res['flooringsystem_en']    = self::getFlooringSystem($this->fs);
            $res['flooringsystem_tc']    = $view->t(self::getFlooringSystem($this->fs), Model_Translate::TC);
        }        
        $res['airconhoursweek']          = (string)$this->ahw;

        $res['airconhourssaturday']      = (string)$this->ahs;
        $res['salepricepersqft']         = (string)$this->spps;
        $res['salepricetotal']           = (string)$this->spt;
        $res['rentpricepersqft']         = (string)$this->rpps;
        $res['rentpricetotal']           = (string)$this->rpt;

        if (!empty($this->os)) {
            $res['ownership']    = (string)$this->os;
            $res['ownership_en'] = self::getOwnerShip($this->os);
            $res['ownership_tc'] = $view->t(self::getOwnerShip($this->os), Model_Translate::TC);
        }        
        foreach ((array)$this->foc as $data) {
            $res['fitoutconditions']    = (string)$data;
            $res['fitoutconditions_en'] = self::getFitoutConditions($data);
            $res['fitoutconditions_tc'] = $view->t(self::getFitoutConditions($data), Model_Translate::TC);
        }
        foreach ((array)$this->av as $data) {
            $res['availability'] = (string)$data;
            $res['availability_en'] = self::getAvailabilitySearch($data);
            $res['availability_tc'] = $view->t(self::getAvailabilitySearch($data), Model_Translate::TC);
        }
        foreach ((array)$this->acs as $data) {
            $res['airconsystem']    = (string)$data;
            $res['airconsystem_en'] = self::getAirConditioningSystemSearch($data);
            $res['airconsystem_tc'] = $view->t(self::getAirConditioningSystemSearch($data), Model_Translate::TC);
        }
        foreach ((array)$this->to as $data) {
            if (!empty($data)) {
                $res['toilet']    = (string)$data;
                $res['toilet_en'] = self::getToilet($data);
                $res['toilet_tc'] = $view->t(self::getToilet($data), Model_Translate::TC);
            }
        }
        foreach ((array)$this->bf as $data) {
            $res['buildingfacilities']    = (string)$data;
            $res['buildingfacilities_en'] = self::getBuildingFacilities($data);
            $res['buildingfacilities_tc'] = $view->t(self::getBuildingFacilities($data), Model_Translate::TC);
        }
        foreach ((array)$this->cpf as $data) {
            $res['carparkingfacilities']    = (string)$data;
            $res['carparkingfacilities_en'] = self::getCarparkingFacilities($data);
            $res['carparkingfacilities_tc'] = $view->t(self::getCarparkingFacilities($data), Model_Translate::TC);           
        }        
        return $res;
    }
    


    public function processRestForm()
    {
        $post = $_POST;

        if (!empty($_POST['building'])) {
            //$this->location = Model_Location::getDistrictId($_POST['district']);
        }

        //Size
        if (!empty($_POST['size']) && intval($_POST['size']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for size');
        }
        if (!empty($_POST['size'])) {
            $this->size = intval($_POST['size']);
        }

        //Sale price
        if (!empty($_POST['sale_price']) && intval($_POST['sale_price']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for sale price');
        }
        if(!empty($_POST['sale_price'])) {
            $this->sale_price = $_POST['sale_price'];
        }

        //Rent price
        if (!empty($_POST['rent_price']) && intval($_POST['rent_price']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for rent price');
        }
        if(!empty($_POST['rent_price'])) {
            $this->rent_price = $_POST['rent_price'];
        }
        
       
        //Property Type
        $values = self::getPropertyTypePostAd();
        $key    = trim($_POST['property_type']);
        
//        var_dump($key, $values[$key], array_search($key, $values));

        if (!empty($key) &&
                empty($values[$key]) && array_search($key, $values) === false) {
            throw new Ac_Exception_MissingInformation('Property Type is empty');
        }
        if (!empty($values[$key])) {
            $this->property_type = intval($key);
        } elseif(($res = array_search($key, $values)) !== false) {
            $this->property_type = intval($res);
        }
       
        
        parent::processRestForm();
        return true;
    }    
}
